package cn.semcorp.zhuhaizj.services.impl;

import cn.semcorp.zhuhaizj.common.Common;
import cn.semcorp.zhuhaizj.exception.ServiceException;
import cn.semcorp.zhuhaizj.mapper.TrainingMapper;
import cn.semcorp.zhuhaizj.pojo.dto.*;
import cn.semcorp.zhuhaizj.pojo.entity.BatchTrainingEntity;
import cn.semcorp.zhuhaizj.pojo.entity.CommonEntity;
import cn.semcorp.zhuhaizj.pojo.vo.*;
import cn.semcorp.zhuhaizj.repo.IRedisRepository;
import cn.semcorp.zhuhaizj.restful.JsonPage;
import cn.semcorp.zhuhaizj.restful.JsonResult;
import cn.semcorp.zhuhaizj.restful.ResponseCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

import static cn.semcorp.zhuhaizj.common.Common.*;
import static cn.semcorp.zhuhaizj.quartzJob.TobeTrainingJob.isYYYYMMDD;
import static cn.semcorp.zhuhaizj.repo.IRedisRepository.OPERATOR_ITEM_KEY;

@Service
@Slf4j
public class TrainingServiceImpl {
    @Autowired
    private TrainingMapper mapper;
    @Autowired
    private IRedisRepository redisTemplate;

    /**
     * 查询所有的课程列表
     * @return
     */
    public List<TrainingDataVO> selectTrainingClassList() {
        return mapper.selectTrainingClassList();
    }

    /**
     * 修改课程信息
     *
     * @param trainingDataDTO
     */
    public void updateTraining(TrainingDataDTO trainingDataDTO) {
        mapper.updateTraining(trainingDataDTO);
    }

    /**
     * 新增
     * @param trainingDataDTO
     */
    public Integer add(TrainingDataDTO trainingDataDTO) {
        return mapper.add(trainingDataDTO);
    }

    /**
     * 添加人员
     */
    public int addPeople(AddPeopleDTO addPeopleDTO) {
        String inputTime = addPeopleDTO.getDate();
        if(isYYYYMMDD(inputTime)){
            long days = Common.howMuchDaysBetween1(inputTime);
            if (days <= 180){
                addPeopleDTO.setPlan("新人养成");
            }else{
                addPeopleDTO.setPlan("能力打造");
            }
        }
        return mapper.insertListF(addPeopleDTO);
    }

    /**
     * 导入培训记录
     */
    public void addRecords(List<InsertRecordDTO> list) {
        Pattern pattern = Pattern.compile(Common.regex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 指定你想要的日期格式
        for (InsertRecordDTO insertAssessDTO : list) {
            if (!pattern.matcher(insertAssessDTO.getEnforceDate()).matches()){
                throw new ServiceException(ResponseCode.BAD_REQUEST,"日期格式错误,请提供纯数字格式!");
            }
            // 转换Excel序列号为Java Date对象
            Date dateValue = new Date((long)(Double.parseDouble(insertAssessDTO.getEnforceDate()) - 25569) * (24 * 60 * 60 * 1000)); // Excel 1900日期系统需要减去25569
            // 格式化日期
            String formattedDate = sdf.format(dateValue);
            insertAssessDTO.setEnforceDate(formattedDate);
        }
        mapper.addRecords(list);
    }

    /**
     * 根据id删除课程
     */
    public Integer deleteById(String id) {
        return mapper.deleteById(Integer.parseInt(id));
    }

    /**
     * 初始化
     * @return
     */
    public List<FlowerUserDTO> selectFlowerList() {
        log.info("正在执行查询人员信息业务...");
        List<FlowerUserDTO> flowersList = redisTemplate.getFlowersList();
        if (flowersList.size() != 0){
            log.info("查询人员信息redis缓存命中成功!");
            return flowersList;
        }
        log.info("redis缓存命中失败,开始执行查询Mysql业务...");
        List<FlowerUserDTO> flowerUserDTOS = mapper.selectFlowerList();
        log.info("执行查询Mysql业务成功,开始向Redis缓存...");
        redisTemplate.saveFlowersList(flowerUserDTOS);
        log.info("redis缓存人员信息成功!");
        return flowerUserDTOS;
    }

    public List<FlowerUserDTO> selectFlowerListCondition() {
//        return mapper.selectFlowerListCondition(common97);
        return mapper.selectFlowerList();
    }

    public List<FlowerUserDTO> selectFlowerListOther() {
        return mapper.selectFlowerListOther(objValue66,objValue67);
    }

    /**
     * 修改花名册人员信息
     *
     * @param dto
     */
    public Integer updatePeopleById(UpdatePeopleDTO dto) {
        return mapper.updatePeopleById(dto);
    }

    /**
     * 根据id查询人员信息
     *
     * @param id
     */
    public FlowerUserDTO selectFlowerUserById(String id) {
        return mapper.selectFlowerUserById(id);
    }

    /**
     * 模糊查询
     */
    public List<FlowerUserDTO> selectMH(String content) {
        return mapper.selectMH(content);
    }

    /**
     * 导入年度教育培训计划
     */
    public Integer inputEducationPlan(List<TrainingInputEducationDTO> list) {
        mapper.deleteEducationPlan();
        return mapper.inputEducationPlan(list);
    }

    /**
     * 导入年度技能培训计划
     */
    public Integer inputSkillPlan(List<TrainingInputSkillDTO> list) {
        mapper.deleteSkillPlan();
        return mapper.inputSkillPlan(list);
    }

    /**
     * 查询年度教育计划计划
     */
    public List<TrainingInputEducationVO> selectEducationList() {
        return mapper.selectEducationList();
    }

    /**
     * 查询年度技能培训计划
     */
    public List<TrainingInputSkillVO> selectSkillList() {
        return mapper.selectSkillList();
    }

    /**
     * 查询考试记录列表
     */
    public JsonPage<RecordDTO> selectTestRecordList(Integer pageNum, Integer pageSize) {
//        redisTemplate.deleteRecord();
//        long start = (long) pageSize * (pageNum - 1);
//        long end = (long) pageSize * pageNum - 1;

//        log.info("从Redis查询培训记录缓存数据执行中...");
//        List<RecordDTO> list = redisTemplate.getAllRecords();
//        if (list.size() != 0 && pageNum == 1){
//            log.info("从Redis查询培训记录缓存数据命中!");
//            return JsonPage.restPage(new PageInfo<>(list));
//        }
//        if (pageNum != 1){
//            log.info("从Redis查询培训记录缓存数据命中!");
//            return JsonPage.restPage(new PageInfo<>(redisTemplate.getAllRecords(start,end)));
//        }
//        log.info("从Redis查询人员架构缓存数据命中失败,开始执行查询业务逻辑...");
        PageHelper.startPage(pageNum, pageSize);
        List<RecordDTO> recordDTOS = mapper.selectTestRecordList();
//        log.info("查询培训记录业务成功!");
//        log.info("向Redis缓存培训记录数据执行中...");
//        redisTemplate.saveTrainingRecord(recordDTOS);
//        log.info("向Redis缓存培训记录数据成功!");
        return JsonPage.restPage(new PageInfo<>(recordDTOS));
    }

    /**
     * 查询培训记录列表
     */
    public JsonPage<RecordDTO> selectTrainingRecordList(Integer pageNum, Integer pageSize) {
//        redisTemplate.deleteRecord();
//        long start = (long) pageSize * (pageNum - 1);
//        long end = (long) pageSize * pageNum - 1;

//        log.info("从Redis查询培训记录缓存数据执行中...");
//        List<RecordDTO> list = redisTemplate.getAllRecords();
//        if (list.size() != 0 && pageNum == 1){
//            log.info("从Redis查询培训记录缓存数据命中!");
//            return JsonPage.restPage(new PageInfo<>(list));
//        }
//        if (pageNum != 1){
//            log.info("从Redis查询培训记录缓存数据命中!");
//            return JsonPage.restPage(new PageInfo<>(redisTemplate.getAllRecords(start,end)));
//        }
//        log.info("从Redis查询人员架构缓存数据命中失败,开始执行查询业务逻辑...");
        PageHelper.startPage(pageNum, pageSize);
        List<RecordDTO> recordDTOS = mapper.selectTrainingRecordList();
//        log.info("查询培训记录业务成功!");
//        log.info("向Redis缓存培训记录数据执行中...");
//        redisTemplate.saveTrainingRecord(recordDTOS);
//        log.info("向Redis缓存培训记录数据成功!");
        return JsonPage.restPage(new PageInfo<>(recordDTOS));
    }

    /**
     * 根据姓名查询所有考试记录
     * @return
     */
    public JsonPage<RecordDTO> selectTestRecordByCondition(SelectTestRecordByNameDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RecordDTO> recordDTOS = mapper.selectTestRecordByCondition(dto);
        return JsonPage.restPage(new PageInfo<>(recordDTOS));
    }

    /**
     * 根据条件查询所有培训记录
     * @return
     */
    public JsonPage<RecordDTO> selectTrainingRecordByCondition(SelectTrainingRecordByNameDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<RecordDTO> recordDTOS = mapper.selectTrainingRecordByCondition(dto);
        return JsonPage.restPage(new PageInfo<>(recordDTOS));
    }


    /**
     * 月生成技能认定计划
     */
    public String skillPlanCheck(){
        LocalDate nowDate = Common.getNowDate();
        String year = String.valueOf(nowDate.getYear());
        String month = String.valueOf(nowDate.getMonthValue());
        String yearMonth = formatterDate(year, month);
        List<SelectSkillPlan> selectSkillPlans = mapper.selectSkillPlanListInsert(yearMonth);
        if (selectSkillPlans.size() != 0) {
            return "核查成功,技能认定月度计划已生成,不能重复操作!";
        }

        List<TrainingInputSkillVO> list = skillPlanCheck_Bro(year, month);
        if (list.size() == 0){
            return "核查成功,本月无待完成技能认定月度计划!";
        }
        mapper.insertSkillPlan(list);
        return "核查成功!技能认定月度计划生成成功!";
    }

    /**
     * 月生成教育培训计划
     */
    public String educationPlanCheck(){
        LocalDate nowDate = Common.getNowDate();
        String year = String.valueOf(nowDate.getYear());
        String month = String.valueOf(nowDate.getMonthValue());
        String yearMonth = formatterDate(year, month);
        List<SelectEducationPlan> selectEducationPlans = mapper.selectEducationPlanListInsert(yearMonth);
        if (selectEducationPlans.size() != 0){
            return "核查成功,教育培训月度计划已生成,不能重复操作!";
        }

        List<TrainingInputEducationVO> list = educationPlanCheck_Bro(year, month);
        if (list.size() == 0){
            return "核查成功,本月无待完成教育培训月度计划!";
        }
        mapper.insertEducationPlan(list);
        return "核查成功!教育培训月度计划生成成功!";
    }
    /**
     * 查询当月待完成教育计划 - 生成计划辅助
     * @param year
     * @param month
     * @return
     */
    public List<TrainingInputEducationVO> educationPlanCheck_Bro(String year, String month) {
//        StringBuilder name = new StringBuilder();
//        List<String> nameList =  mapper.selectFlowerListName();
//        for (int i = 0; i <nameList.size(); i++) {
//            if (i == nameList.size()-1){
//                name.append(nameList.get(i));
//                continue;
//            }
//            name.append(nameList.get(i)).append(",");
//        }

        String yearMonth = formatterDate(year, month);
        month = "m" + month;
        List<TrainingInputEducationVO> list = mapper.educationPlanCheck(month, icon1);
        for (TrainingInputEducationVO trainingInputEducationVO : list) {
            String operator = trainingInputEducationVO.getOperator();
//            if ()

            trainingInputEducationVO.setModel(objValue4);
            trainingInputEducationVO.setState(objValue3);
            trainingInputEducationVO.setOtherNotes(objValue2);
//            trainingInputEducationVO.setPersonShould(name.toString()); // 需要完成的人
            trainingInputEducationVO.setYearMonth(yearMonth);
        }


        return list;
    }

    /**
     * 查询技能认定月计划
     * @return
     */
    public List<SelectSkillPlan> selectSkillPlanList(){
        return mapper.selectSkillPlanList();
    }

    /**
     * 查询教育培训月计划
     * @return
     */
    public List<SelectEducationPlan> selectEducationPlanList(){
//        LocalDate nowDate = Common.getNowDate();
//        String year = String.valueOf(nowDate.getYear());
//        String month = String.valueOf(nowDate.getMonthValue());
//        String yearMonth = formatterDate(year, month);
        return mapper.selectEducationPlanList();
    }

    /**
     * 完成任务,  修改计划状态 - 教育
     */
    public int updateEducationPlanStateById(String id) throws Throwable {
        CommonEntity commonEntity = mapper.queryEducationPlanStateById(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date = sdf.parse(commonEntity.getYearMonth());
        // 通过获得月份值
        String month = String.valueOf(date.getMonth() + 1); // Date类中月份从 0 开始，所以要加 1
        mapper.updateEducationPlanCompletedYqToYes("m"+month,icon2,commonEntity.getProject());
        return mapper.updateEducationPlanStateById(id,common1);
    }

    /**
     * 完成任务, 修改计划状态- 技能
     * @param id
     * @return
     * @throws ParseException
     */
    public int updateSkillPlanStateById(String id) throws Throwable {
        CommonEntity commonEntity = mapper.querySkillPlanStateById(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date = sdf.parse(commonEntity.getYearMonth());
        // 通过获得月份值
        String month = String.valueOf(date.getMonth() + 1); // Date类中月份从 0 开始，所以要加 1
        mapper.updateSkillPlanCompletedYqToYes("m"+month,icon2,commonEntity.getProject());
        return mapper.updateSkillPlanStateById(id,common1);
    }

    /**
     * 查询当月待完成培训任务 - 生成计划辅助
     * @param year
     * @param month
     */
    public List<TrainingInputSkillVO> skillPlanCheck_Bro(String year, String month) {
        String yearMonth = formatterDate(year, month);
        month = "m" + month;

        // 培训对象确认
        List<String> bz = redisTemplate.getFlowers(IRedisRepository.MONITOR_ITEM_KEY);
        List<String> zc = redisTemplate.getFlowers(IRedisRepository.MAIN_ITEM_KEY);
        List<String> czg = redisTemplate.getFlowers(OPERATOR_ITEM_KEY);


        log.info("从Redis查询岗位类别人员缓存数据执行中...");
        if (czg != null && czg.size() != 0){
            log.info("Redis查询操作工人员缓存数据命中成功!");
        }else{
            log.info("Redis查询岗位类别缓存数据命中失败,开始执行查询业务逻辑...");
            czg = mapper.selectFlowerListByPostClass("操作工","制浆");
            redisTemplate.saveFlowersOperator(czg);
            log.info("查询操作工人员岗位类别业务执行完成,Redis缓存成功!");
        }

        if (zc != null && zc.size() != 0){
            log.info("Redis查询主操人员缓存数据命中成功!");
        }else{
            log.info("Redis查询岗位类别缓存数据命中失败,开始执行查询业务逻辑...");
            zc = mapper.selectFlowerListByPostClass("主操","制浆");
            redisTemplate.saveFlowersMain(zc);
            log.info("查询主操人员岗位类别业务执行完成,Redis缓存成功!");
        }
        if (bz != null && bz.size() != 0){
            log.info("Redis查询班长人员缓存数据命中成功!");
        }else{
            log.info("Redis查询岗位类别缓存数据命中失败,开始执行查询业务逻辑...");
            bz = mapper.selectFlowerListByPostClass("班长","制浆");
            redisTemplate.saveFlowersMonitor(bz);
            log.info("查询班长人员岗位类别业务执行完成,Redis缓存成功!");
        }

        // 查询技能认定待完成
        List<TrainingInputSkillVO> list = mapper.skillPlanCheck(month, icon1);
        for (TrainingInputSkillVO trainingInputSkillVO : list) {
            StringBuilder name = new StringBuilder();
            trainingInputSkillVO.setModel(objValue5);
            trainingInputSkillVO.setState(objValue3);
            trainingInputSkillVO.setOtherNotes(objValue2);
            trainingInputSkillVO.setYearMonth(yearMonth);
            String operator = trainingInputSkillVO.getOperator();
            String main = trainingInputSkillVO.getMain();
            String monitor = trainingInputSkillVO.getMonitor();
            if (operator != null){
                for (int i = 0; i <czg.size(); i++) {
                    name.append(czg.get(i)).append(",");
                }
            }
            if (main != null){
                for (String s : zc) {
                    name.append(s).append(",");
                }
            }
            if (monitor != null){
                for (String s : bz) {
                    name.append(s).append(",");
                }
            }
            if (name.length() != 0){
                name.replace(name.length()-1,name.length(),"");
            }
            trainingInputSkillVO.setPersonShould(name.toString()); // 需要完成的人
        }
        return list;
    }


    public static String formatterDate(String year,String month){
        int yearInt = Integer.parseInt(year);
        int monthInt = Integer.parseInt(month);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        try {
            Date date = sdf.parse(yearInt + "-" + monthInt);
            return sdf.format(date);
        } catch (ParseException e) {
            throw new ServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"解析错误,查询失败");
        }
    }

    /**
     * 统计
     * @return
     */
    public Integer countEducationPlanByMonth() {
        LocalDate nowDate = Common.getNowDate();
        String year = String.valueOf(nowDate.getYear());
        String month = String.valueOf(nowDate.getMonthValue());
        String yearMonth = formatterDate(year, month);
        return mapper.countEducationPlanByMonth(yearMonth,common2);
    }

    public Integer countSkillPlanByMonth() {
        LocalDate nowDate = Common.getNowDate();
        String year = String.valueOf(nowDate.getYear());
        String month = String.valueOf(nowDate.getMonthValue());
        String yearMonth = formatterDate(year, month);
        return mapper.countSkillPlanByMonth(yearMonth,common2);
    }

    /**
     * 上传图片 - 教育
     * @param outId
     * @param date
     * @param base64Data
     */
    public Integer insertEducationPicture(String outId, String date, String base64Data) {
        return mapper.insertEducationPicture(outId,date,base64Data);
    }

    /**
     * 上传图片 - 技能
     * @param outId
     * @param date
     * @param base64Data
     */
    public Integer insertSkillPicture(String outId, String date, String base64Data) {
        return mapper.insertSkillPicture(outId,date,base64Data);
    }

    /**
     * 查询上传照片 - 教育
     * @param id
     * @return List<String>
     */
    public List<String> queryEducationPictureById(String id) {
        return mapper.queryEducationPictureById(id);
    }

    /**
     * 查询上传照片 - 技能
     * @param  id
     * @return  List<String>
     */
    public List<String> querySkillPictureById(String id) {
        return mapper.querySkillPictureById(id);
    }

    /** tobe 待完成
     * 判断是否上传过结果
     */
    public Integer queryEducationPictureCountById(String id) {
        return mapper.queryEducationPictureCountById(id);
    }

    public Integer querySkillPictureCountById(String id) {
        return mapper.querySkillPictureCountById(id);
    }

    /**
     * 根据id删除培训记录
     * @param id
     * @return
     */
    // TODO
    public Integer deletePeopleById(String id) {
//        FlowerUserDTO flowerUserDTO = mapper.selectFlowerUserById(id);
        // 删除相关培训记录和学习计划
//        log.info("正在执行删除<{}>历史考试记录中...",flowerUserDTO.getName());
//        mapper.deleteTestRecordById(flowerUserDTO.getName());
//        log.info("执行删除<{}>历史考试记录成功!",flowerUserDTO.getName());
//
//        log.info("正在执行删除<{}>历史培训计划记录中...",flowerUserDTO.getName());
//        mapper.deleteStudyPlanById(id);
//        log.info("执行删除<{}>历史培训计划记录成功!",flowerUserDTO.getName());
//
//        log.info("正在执行删除<{}>考试计划中...",flowerUserDTO.getName());
//        mapper.deleteTestIngRecordById(id);
//        log.info("执行删除<{}>考试计划成功!",flowerUserDTO.getName());
//
//        log.info("正在执行删除<{}>培训计划中...",flowerUserDTO.getName());
//        mapper.deleteStudyIngPlanById(id);
//        log.info("执行删除<{}>培训计划成功!",flowerUserDTO.getName());
        return mapper.deletePeopleById(id);
    }

    /**
     * 批量创建的培训任务, 生成多条记录
     * @param dto
     * @return
     */
    public Integer batchTrainingInsert(BatchTrainingDTO dto) {
        List<BatchTrainingEntity> list = new ArrayList<>();
        String[] objs = dto.getObjs();
        // 根据课程代码查询课程其他信息
        String classCode = dto.getClassCode();
        CoursesVO coursesVO = mapper.selectCoursesByClassCode(classCode);

        // 根据姓名查询人员其他信息
        for (String name : objs) {
            BatchTrainingEntity a = new BatchTrainingEntity();
            FlowerUserVO flowerUserVO = mapper.selectPeopleByName(name);

            a.setName(flowerUserVO.getName());
            a.setWorkNumber(flowerUserVO.getWorkNumber());
            a.setWorkshop(flowerUserVO.getWorkshop());
            a.setPost(flowerUserVO.getPost());
            a.setDepartment(flowerUserVO.getDepartment());

            a.setClassCode(coursesVO.getClassCode());
            a.setClassModel(coursesVO.getClassModel());
            a.setTrainingModel(coursesVO.getTrainingModel());
            a.setTrainingTopic(coursesVO.getTrainingTopic());
            a.setTrainingContent(coursesVO.getTrainingContent());
            a.setTrainingMethod(dto.getTrainingMethod());

            a.setEnforceDate(dto.getEnforceDate());
            a.setEnforcePlace(dto.getEnforcePlace());
            a.setEnforceDepartment(dto.getEnforceDepartment());
            a.setAppraiseLevel(dto.getAppraiseLevel());
            a.setAppraiseMethod(dto.getAppraiseMethod());
            a.setAppraiseTime(dto.getAppraiseTime());
            a.setAppraiseDate(dto.getAppraiseDate());
            a.setAppraiseResult(dto.getAppraiseResult());
            a.setEnforcer(dto.getEnforcer());
            a.setApprover(dto.getApprover());
            list.add(a);
        }
        int rows = mapper.batchTrainingInsert(list);
        if (rows != list.size()){
            return 2;
        }
        return 1;
    }

    /**
     * 查询所有的课程代码列表
     * @return
     */
    public List<String> selectCodeList() {
        return mapper.selectCodeList();
    }

    /**
     * 根据id删除课程
     * @param id
     * @return
     */
    public void deleteTrainingById(String id) {
        mapper.deleteTrainingById(id);
    }

    /**
     * 查询所有的课程类别
     * @return
     */
    public List<String> selectClassModelList() {
        return mapper.selectClassModelList();
    }


    /**
     * 根据课程类别查询对应的课程代码
     * @param classModel
     * @return
     */
    public List<String> selectClassCodeByClassModel(String classModel) {
        return mapper.selectClassCodeByClassModel(classModel);

    }

    /**
     * 根据课程代码查询对应的课程主题和内容
     * @param classCode
     * @return
     */
    public TCVO selectTopicContentByClassCode(String classCode) {
        return mapper.selectTopicContentByClassCode(classCode);
    }

    /**
     * 添加考试计划(临时)
     * @param list
     * @return
     */
    public int addTestPlan(List<StudyDTO> list) {
        for (StudyDTO studyDTO : list) {
            studyDTO.setCreateDate(String.valueOf(Common.getNowDate()));
            studyDTO.setOtherNotes(objValue1);
        }
        return mapper.addTestPlan(list);
    }

    /**
     * 添加培训计划(临时)
     * @param list
     * @return
     */
    public int addStudyPlan(List<StudyDTO> list) {
        for (StudyDTO studyDTO : list) {
            studyDTO.setCreateDate(String.valueOf(Common.getNowDate()));
        }
        return mapper.addStudyPlan(list);
    }

    /**
     * 根据id查询人员信息
     * @param id
     * @return
     */
    public SelectFlowerByVO selectFlowerById(String id) {
        SelectFlowerByVO selectFlowerByVO = mapper.selectFlowerById(id);
        selectFlowerByVO.setCountYear(String.valueOf(Common.getNowDate().getYear()));
        return selectFlowerByVO;
    }

    /**
     * 查询考试计划列表
     */
    public List<StudyVO> selectTestList() {
        //objValue6
        return mapper.selectTestList(objValue6);
    }

    /**
     * 查询培训计划列表
     */
    public List<StudyVO> selectTrainingList() {
        //objValue6
        return mapper.selectTrainingList1(objValue74);
    }

    public void uploadStudyPlanById(String id, String base64) {
        if (id == null || id.equals("")){
            throw new ServiceException(ResponseCode.BAD_REQUEST,"上传指向不能为空!");
        }
        id = id.substring(0, id.length()-1);
        String[] gs = id.split("g", -1);
        for (String idItem : gs) {
            mapper.uploadStudyPlanById(idItem,base64);
        }
    }

    /**
     * 根据id查询学习计划的照片
     * @param id
     * @return
     */
    public List<String> queryStudyPictureById(String id) {
        return mapper.queryStudyPictureById(id);
    }


    /**
     * 查询学习计划是否上传过结果
     * @param id
     * @return
     */
    public int queryStudyPictureCountById(String id) {
        return mapper.queryStudyPictureCountById(id);
    }

    /**
     * 根据id修改考试计划状态
     * @param list
     * @return
     */
    public void updateTestById(List<StudyUpdateDTO> list) {
        for (StudyUpdateDTO studyDTO : list) {
            // 修改表记录完成状态
            mapper.updateTestById(studyDTO.getId(),studyDTO.getResult(),true);

            // 查询,并添加到考试记录表
            StudyDTO studyVO = mapper.selectTestListById(studyDTO.getId());
            mapper.insertTestTrainingRecord(studyVO);
        }
    }


    /**
     * 根据id修改培训计划状态
     * @param list
     * @return
     */
    public void updateTrainingById(List<StudyDTO> list) {
        for (StudyDTO studyDTO : list) {
            // 修改表记录完成状态
            mapper.updateTrainingById(studyDTO.getId(),studyDTO.getAppraiseResult(),true);

            // 查询,并添加到培训记录表
            StudyDTO studyVO = mapper.selectTrainingListById(studyDTO.getId());
            mapper.insertTrainingRecord(studyVO);
        }
    }

    /**
     * 根据姓名查询奖惩记录 -> 奖次数统计
     * @param name
     * @return
     */
    public Map<String,List<String>> selectCountAssessAllByName(String name) {
        Map<String,List<String>> map = new HashMap<>();
        // 查询所有的违反类型
        List<String> list = mapper.selectViolateList();
        // 查询考核中,  按考核类型奖罚的次数
        for (String violate : list) { // 执行力
            // 次数
            List<String> listAdd = new ArrayList<>();
            String numberYes = mapper.selectAssessByViolate(violate,name,common3); // 次数
            String numberNo = mapper.selectAssessByViolate(violate,name,common4); // 次数
            // 只查加分
            SelectCountAssessAllVO point = mapper.selectAssessColumnByViolateOrPunish(violate,name);
            listAdd.add(numberYes); // 奖次数
            listAdd.add(numberNo); // 罚次数
            listAdd.add(point.getResult1()); // 绩效扣分
            listAdd.add(point.getResult2()); // 绩效扣比
            listAdd.add(point.getResult3()); // 罚款
            listAdd.add(point.getResult4()); // 现金奖励
            listAdd.add(point.getResult5()); // 绩效加分
            map.put(violate,listAdd);
        }
        return map;
    }

    /**
     * 根据id删除学习计划
     * @param id
     */
    public void deleteStudyById(Integer id) {
        mapper.deleteStudyById(id); // 删除计划
    }

    /**
     * 根据id查询员工的能力矩阵图
     * @param name
     * @return
     */
    // 修改
    public Map<String,String> selectAblePictureByName(String name) {
        Map<String,String> returnMap = new HashMap<>();// 返回
        Map<String,List<String>> mapModel = new HashMap<>();
        List<String> trainingModel = mapper.selectClassModel(); // 安全 SOP SOC 技能 管理
        for (String training : trainingModel) {
            // 找到考核下属类型
            List<String> list = mapper.selectAssessModelByTrainingModel(training);
            // 不做判断
            mapModel.put(training, list);
        }
        // 逻辑  管理  技能
        for (String test : trainingModel) { // 培训类型
            if (test == null){
                continue;
            }
            String basicResult = "-" ;

            String result ;
            String numberYes = mapper.selectTrainingRecordByYes1(name,test,common5); // 合格次数
            String numberAll= mapper.selectTrainingRecordByIdAllS(name,test,objValue6); // 总次数
            if (Double.parseDouble(numberAll) != 0) { // 证明有培训
                if (Double.parseDouble(numberYes) != 0) {
                    basicResult =
                            String.valueOf(Double.parseDouble(transformTwoNumber((Double.parseDouble(numberYes) / Double.parseDouble(numberAll)) * 100)));
                }else{
                    basicResult = "0"; // 没一次合格
                }
            }

            // 波动因数
            double pdResult = 0;
            double paResult = 0;
            double deResult = 0;
            double fiResult = 0;
            double reResult = 0;
            double pbpResult = 0;
            List<String> assessList = mapModel.get(test);
            for (String assess : assessList) {  // 培训下属类型
                SelectResultVO srv = mapper.selectResultByAssess(assess,name);
                if (srv == null){
                    continue;
                }
                pdResult += srv.getPd()/250; // 减
                paResult += srv.getPa()/100; // 减
                deResult += srv.getDe()*10; // 降
                fiResult += srv.getFi()/150; // 减
                reResult += srv.getRe()/150; // 加
                pbpResult += srv.getPbp()/250; // 加
            }
            if (isNumber(basicResult)){ // 如果有基础值的话
                double noResult = pdResult + paResult + deResult + fiResult;
                double yesResult = reResult + pbpResult;
                // 有培训过
                result = Common.transformTwoNumber(Double.parseDouble(basicResult) + yesResult - noResult);
                if (Double.parseDouble(result) >= 100){
                    result = "100.0";
                }
            }else{
                result = "-";
            }
            returnMap.put(test,result);
        }
        return returnMap;
    }

    /**
     * 根据id查询员工所有培训结果统计
     * @param name
     * @return
     */
    public List<SelectPassAbleTwoVO> selectPassPictureByName(String name) {
        List<SelectPassAbleTwoVO> list = new ArrayList<>();
//        List<String> allAbles = mapper.selectAllAbleDistinct();
        List<String> allAbles = mapper.selectClassModel();

        for (String able : allAbles) {
            SelectPassAbleTwoVO s = new SelectPassAbleTwoVO();
            String syes = mapper.selectTrainingRecordByYes(name, able,common5); // 通过记录
            String sall = mapper.selectTrainingRecordByYes(name, able,null); // 培训总记录
//            String sall = mapper.selectTrainingRecordByIdAll(name,able);// 培训总次数
            s.setAble(able);
            double yes = Double.parseDouble(syes);
            double all = Double.parseDouble(sall);
            if (all > 0){
                s.setAbleCount(sall);
                s.setValueYes(transformOneNumber(yes/all*100));
                s.setValueNo(transformOneNumber((1-yes/all)*100));
                list.add(s);
                continue;
            }
            // 没有培训过
            s.setValueYes("-");
            s.setValueNo("-");
            s.setAbleCount("-");
            list.add(s);
        }
        return list;
    }

    /**
     * 根据姓名查询员工的课程完成进度
     * @param name
     * @return
     */
    public List<SelectProgressAbleVO> selectProgressPictureById(String name) {
        List<SelectProgressAbleVO> list = new ArrayList<>();
        List<String> allAbles = mapper.selectClassModel();
        for (String able : allAbles) {
            SelectProgressAbleVO s = new SelectProgressAbleVO();
            // 该种类别下,  学习了多少个课程
            String studied = mapper.selectAbleStudySubject(name, able); // 5
            // 该种课程类别下,  一共有多少个可学习的课
            String all = mapper.selectAbleAllSubject(able);// 该类别 总课程数 32
            s.setAble(able);
            if (all == null || all.equals("0")){
                s.setPercent("-");
                list.add(s);
                continue;
            }
            s.setPercent(transformTwoNumber(Double.parseDouble(studied)/Double.parseDouble(all)*100));
            list.add(s);
        }
        return list;
    }

    /**
     * 创建晋升计划
     * @param list
     */
    public void addPromotionPlan(ArrayList<AddPromotionDTO> list) {
        for (AddPromotionDTO addPromotionDTO : list) {
            addPromotionDTO.setState("等待结果");
        }
        if (list.size() == 1) {
            mapper.addPromotionPlanOne(list.get(0));
            return;
        }
        mapper.addPromotionPlan(list);
    }

    /**
     * 查询所有的晋升计划
     * @return
     */
    public List<SelectPromotionVO> selectPromotionList() {
        //mapper.selectRecordLastDate()
        return mapper.selectPromotionList();
    }

    /**
     * 根据日期对晋升计划结果 =>   等待复判
     * @param date
     * @return
     */
    public List<SelectPromotionVO> selectPromotionByDate(String date) {
        return mapper.selectPromotionByDate(date);
    }

    /**
     * 查询所有的晋升计划统计, 最近一次
     * @return
     */
    public String countAuditPlan() {
        return mapper.countAuditPlan(objValue6);
    }

    /**
     * 根据id修改晋升计划中的考核结果(通过)
     * @param id
     */
    public void updatePromotionStateSuccessById(String id) {
        // 修改晋升计划记录的状态
        mapper.updatePromotionStateSuccessById(id);

        // 修改人员的岗位/类别
        PassPromotionVO passPromotionVO = mapper.selectPromotionStateSuccessById(id);
        mapper.updatePeoplePromotion(passPromotionVO);
    }

    /**
     * 根据id修改晋升计划中的考核结果(未通过)
     * @param id
     */
    public void updatePromotionStateNoById(String id) {
        mapper.updatePromotionStateNoById(id);
    }

    /**
     * 根据id修改学习计划中的学习结果,把完成的人去除
     * @param id
     */
    public void updateStudyListByIdList(List<IdDTO> id) {
        StringBuilder str = new StringBuilder();
        if (id.size() == 1){
            //return mapper.updateStudyListByIdList(id.get(0).getId());
        }
        for (int i = 0; i < id.size(); i++) {
            if (i == 0){
                str = new StringBuilder(id.get(i).getId());
            }
            str.append(",").append(id.get(i).getId());
        }
    }

    public void deleteStudyPlanById(String id) {
        mapper.deleteStudyPlanById(id);
    }

    /**
     * 教育计划点击选择完成人提交
     * @param id
     */
    public void selectPersonEducationUpById(String id,List<String> list) {
        List<String> workshopList = getWorkshopList();

        // 待完成记录的人
        String[] shouldName;
        String tobeNames = mapper.selectEducationPlanById(id);
        if (tobeNames != null || tobeNames.length() == 0){
            shouldName = tobeNames.split(",",-1);
        }else{
            shouldName = new String[]{tobeNames};
        }
        // 多人
        StringBuilder workshopCompleted = new StringBuilder();
        StringBuilder tobeList = new StringBuilder();
        for (String tobeName : shouldName) {
            if (list.contains(tobeName)){
                continue;
            }
            tobeList.append(tobeName).append(",");
        }

        String string = tobeList.toString();
        if (tobeList.length() > 0){
            string = tobeList.deleteCharAt(tobeList.length() - 1).toString();
        }
        mapper.selectEducationPersonUpById(id,string,null);

        List<String> tobePersonAfter = new ArrayList<>(Arrays.asList(mapper.selectEducationPlanById(id).split(",",-1)));
        // 车间更新
        for (String workshop : workshopList) {
            // 查到车间所属人员 a b c d e
            boolean bo = true;
            List<String> nameList =  mapper.selectFlowerListByWorkshop(workshop);
            for (String person : tobePersonAfter) { // 待完成 a b
                if (nameList.contains(person)){
                    bo = false;
                    break;
                }
            }
            if (bo){
                workshopCompleted.append(workshop).append(",");
            }
        }
        if (workshopCompleted.length() > 0){
            String workshop1 = workshopCompleted.deleteCharAt(workshopCompleted.length()-1).toString();
            mapper.selectEducationPersonUpById(id,null,workshop1);
        }

    }

    /**
     * 根据技能认定ID选择完成人并提交
     * @param id 技能认定计划的ID
     * @param list 已经选择的完成人列表
     */
    public void selectPersonSkillUpById(String id,List<String> list) {
//        List<String> workshopList = getWorkshopList();
        // 待完成记录的人
        String[] shouldName = new String[0];
        String[] beingName = new String[0];
        // 未完成的人
        String a = mapper.selectSkillPlanById(id);
        if (a != null && a.contains(",")){
            shouldName = a.split(",",-1);
        }
        // 已完成的人
        String b = mapper.selectSkillPlanById2(id);
        if ( b != null &&  b.contains(",")){
            beingName = b.split(",",-1);
        }
        StringBuilder tobeList = new StringBuilder();
        StringBuilder tobeLis2t = new StringBuilder();

        // 查询已完成的人
        for(String t1 : beingName){
            tobeLis2t.append(t1).append(",");
        }

        // 传入完成的人
        for (String t : list){
            tobeLis2t.append(t).append(",");
        }
        tobeLis2t.deleteCharAt(tobeLis2t.length()-1);

        for (String tobeName : shouldName) {
            if (list.contains(tobeName)){
                continue;
            }
            tobeList.append(tobeName).append(",");
        }
        String string = tobeList.toString();
        if (tobeList.length() > 0){
            string = tobeList.deleteCharAt(tobeList.length()-1).toString();
        }
        mapper.selectSkillPersonUpById(id,string,tobeLis2t.toString());
//        mapper.selectSkillPersonUpById(id,string,null);

//        List<String> tobePersonAfter = new ArrayList<>(Arrays.asList(mapper.selectSkillPlanById(id).split(",",-1)));
        // 车间更新
//        for (String workshop : workshopList) {
//            // 查到车间所属人员 a b c d e
//            boolean bo = true;
//            List<String> nameList =  mapper.selectFlowerListByWorkshop(workshop);
//            for (String person : tobePersonAfter) { // 待完成 a b
//                if (nameList.contains(person)){
//                    bo = false;
//                    break;
//                }
//            }
//            if (bo){
//                workshopCompleted.append(workshop).append(",");
//            }
//        }

//        if (workshopCompleted.length() != 0){
//            String workshop1 = workshopCompleted.deleteCharAt(workshopCompleted.length()-1).toString();
//            mapper.selectSkillPersonUpById(id,null,workshop1);
//            return;
//        }

    }


    /**
     * 获取架构信息的方法。
     * 该方法首先尝试从Redis缓存中获取架构信息，如果缓存命中，则直接返回缓存中的数据。
     * 如果缓存未命中，则从数据库中查询相关信息，构建架构信息后存储到Redis中，并返回null。
     * @return SchemaVO 如果缓存中存在架构信息，则返回架构信息对象；否则返回null。
     */

    public SchemaVO getSchema() {
        log.info("从Redis查询人员架构缓存数据执行中...");
        SchemaVO schemaVO1 = redisTemplate.get();
        if (schemaVO1 != null){
            log.info("Redis人员架构缓存数据命中成功!");
            return schemaVO1;
        }
        log.info("Redis人员架构缓存数据命中失败,开始查询执行业务逻辑...");
        List<String> shiftList = getShiftList();
        List<String> workshopList = mapper.selectPulpingWorkshop();
        SchemaVO schemaVO = new SchemaVO();
        List<SchemaVO> down = new ArrayList<>();
        for (String workshop : workshopList) {
            if (workshop == null){
                continue;
            }
            if (workshop.equals(common97)) {
                SchemaVO s = new SchemaVO();
                s.setLabel(workshop);
                List<SchemaVO> wsj = mapper.selectFlowerPostByWorkshopAndShift1(workshop,common96);
                s.setChildren(wsj);
                down.add(s);
                continue;
            }

            if (workshop.equals(common99)){
                SchemaVO s = new SchemaVO();
                List<SchemaVO> wscly = mapper.selectFlowerPostByWorkshopAndShift(workshop,null,common98);
                List<SchemaVO> czg1 = mapper.selectFlowerPostByWorkshopAndShift(workshop,null,common8);
                s.setLabel(workshop);
                wscly.get(0).setChildren(czg1);
                s.setChildren(wscly);
                down.add(s);
                continue;
            }

            SchemaVO s1 = new SchemaVO();
            s1.setLabel(workshop);
            List<SchemaVO> list = new ArrayList<>();
            for (String shift : shiftList) {
                SchemaVO s = new SchemaVO();
                // A1 甲 操作工 => key
                List<SchemaVO> czg = mapper.selectFlowerPostByWorkshopAndShift(workshop,shift,common8);
                // A1 甲 主操 => key
                List<SchemaVO> zc = new ArrayList<>();
                zc = mapper.selectFlowerPostByWorkshopAndShift(workshop,shift,common6);
                if (zc.size() != 0){
                    zc.get(0).setChildren(czg);
                }else{
                    SchemaVO szc = new SchemaVO();
                    szc.setLabel("");
                    szc.setChildren(czg);
                    zc.add(szc);
                }

                // A1 甲 班长 => key
                List<SchemaVO> bz = new ArrayList<>();
                // 先查询班长的管理
                bz = mapper.selectFlowerPostByWorkshopAndShift(workshop,shift,common7);
                if (bz.size() != 0){
                    bz.get(0).setChildren(zc);
                }else{
                    SchemaVO sbz = new SchemaVO();
                    sbz.setLabel("");
                    sbz.setChildren(zc);
                    bz.add(sbz);
                }

                s.setLabel(shift);
                s.setChildren(bz);
                list.add(s);
            }

            s1.setChildren(list);
            down.add(s1);
        }
        List<SchemaVO> gcs = mapper.selectFlowerPostByWorkshopAndShift(null,null,"工程师");
        gcs.get(0).setChildren(down);

        List<SchemaVO> zr = mapper.selectFlowerPostByWorkshopAndShift(null,null,"主任");
        schemaVO.setLabel(zr.get(0).getLabel());
        schemaVO.setChildren(gcs);
/*        log.info("查询人员架构执行业务逻辑成功!");
        // 结果存入redis
        log.info("向Redis加入人员架构缓存数据执行中...");
        redisTemplate.save(schemaVO);
        log.info("向Redis加入人员架构缓存数据执行成功!");*/
        return schemaVO;
    }


    /**
     * 插入考核记录
     * @param list 包含待插入评估信息的列表。列表中的每个元素都应是InsertAssessDTO类型的实例。
     *             InsertAssessDTO是一个数据传输对象，用于封装插入评估所需的各项数据。
     * @return 该方法不返回任何内容。
     */
    public void insertAssess(List<InsertAssessDTO> list) {
        Pattern pattern = Pattern.compile(Common.regex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 指定你想要的日期格式
        for (InsertAssessDTO insertAssessDTO : list) { // 日期和绩效扣比都应为纯数字
            if (!pattern.matcher(insertAssessDTO.getDate()).matches() &&
                    !pattern.matcher(insertAssessDTO.getPerformanceAssess()).matches()){
                throw new ServiceException(ResponseCode.BAD_REQUEST,"日期或总绩效扣除列出现错误,请提供纯数字格式!");
            }

            // 转换Excel序列号为Java Date对象
            Date dateValue = new Date((long)(Double.parseDouble(insertAssessDTO.getDate()) - 25569) * (24 * 60 * 60 * 1000)); // Excel 1900日期系统需要减去25569
            // 格式化日期
            String formattedDate = sdf.format(dateValue);
            insertAssessDTO.setDate(formattedDate);
        }
        mapper.insertAssess(list);
    }

    /**
     * 选择列表查询方法
     * 该方法用于执行一个选择列表的查询操作，但当前实现中并未具体实现查询逻辑，仅返回null作为占位。
     *
     * @return 返回查询结果，当前实现总是返回null。
     */
    public JsonPage<InsertAssessVO> selectSelectList(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        return JsonPage.restPage(new PageInfo<>(mapper.selectSelect()));
    }



    /**
     * 添加评估信息。
     *
     * @param dto 评估信息的插入模式数据传输对象，包含需要添加的评估的详细信息。
     */
    public void addAssess(InsertAssessDTO dto) {
        mapper.addAssess(dto);
    }

    /**
     * 选择并返回违反类型的列表。
     *
     * @return List<String> 返回一个字符串列表，包含违反规定条件的项目。
     */
    public List<String> selectViolateList() {
        return mapper.selectViolateList();
    }

    /**
     * 查询所有的培训时段类型
     * @return
     */
    public List<String> selectTrainingDate() {
        return mapper.selectTrainingDate();
    }

    /**
     * 查询所有的教育类型
     * @return
     */
    public List<String> selectEducationModel() {
        return mapper.selectEducationModel();
    }

    /**
     * 查询所有的培训类型
     * @return
     */
    public List<String> selectTrainingModel() {
        return mapper.selectTrainingModel();
    }

    /**
     * 查询所有课程类型
     * @return
     */
    public List<String> selectClassModel() {
        return mapper.selectClassModel();
    }


    /**
     * 导入课程列表
     * @return
     */
    public void insertTrainingList(List<TrainingDataDTO> list) {
        Pattern pattern = Pattern.compile(regex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 指定你想要的日期格式
        for (TrainingDataDTO trainingDataDTO : list) {
            if (!pattern.matcher(trainingDataDTO.getMakeDate()).matches()) {
                throw new ServiceException(ResponseCode.BAD_REQUEST, "日期格式错误,请提供纯数字格式!");
            }
            // 转换Excel序列号为Java Date对象
            Date dateValue = new Date((long)(Double.parseDouble(trainingDataDTO.getMakeDate()) - 25569) * (24 * 60 * 60 * 1000)); // Excel 1900日期系统需要减去25569

            // 格式化日期
            String formattedDate = sdf.format(dateValue);
            trainingDataDTO.setMakeDate(formattedDate);
        }
        mapper.insertList(list);
    }

    /**
     * 查询人员的考核记录(统计总情况)
     * @param name
     */
    public SelectCountAssessVO selectCountAssessByName(String name) {
        SelectCountAssessVO selectCountAssessVO = mapper.selectCountAssess(name);
        if (selectCountAssessVO == null){
            selectCountAssessVO = new SelectCountAssessVO();
            selectCountAssessVO.setAssess(returnProp1);
            selectCountAssessVO.setDeduct(returnProp2);
            selectCountAssessVO.setDemote(returnProp3);
            selectCountAssessVO.setFines(returnProp4);
            selectCountAssessVO.setPoints(returnProp5);
            selectCountAssessVO.setReward(returnProp6);
        }
        return selectCountAssessVO;
    }

    /**
     * 根据人查询总培训课程的进度,  一段提示
     * @param name
     * @return
     */
    public SelectCountClassVO selectCountClassByName(String name) {
        return mapper.selectCountClassByName(name);
    }

    /**
     * 根据人查询培训课程的总合格率,  一段提示
     * @param name
     * @return
     */
    public SelectCountClassVO selectCountTrainingByName(String name) {
        return mapper.selectCountTrainingByName(name);
    }

    /**
     * 查询所有的岗位类别
     * @return
     */
    public List<String> selectPostClassALl() {
        return mapper.selectPostClassALl();
    }

    /**
     * 根据选择的岗位类别查询岗位
     * @param postClass
     * @return
     */
    public List<String> selectPostByPostClass(String postClass) {
        return mapper.selectPostByPostClass(postClass);
    }

    /**
     * 获取现在所有的制浆车间
     * @return
     */
    public List<String> selectPulpingWorkshop() {
        return mapper.selectPulpingWorkshop();
    }

    /**
     * 获取现在所有的制浆车间 具体的
     * @return
     */
    public List<String> selectPulpingWorkshopCommon() {
        return mapper.selectPulpingWorkshopCommon();
    }

    /**
     * 根据制浆车间获取车间的人员名字
     * @param workshop
     * @return
     */
    public List<String> selectNameByWorkshop(String workshop) {
        return mapper.selectNameByWorkshop(workshop);
    }

    /**
     * 查询默认晋升的岗位和岗位类别
     * @param post
     * @return
     */
    public PromotionUpVO selectNullPromotionUpByPost(String post) {
        PromotionUpVO promotionUpVO = mapper.selectNullPromotionUpByPost(post);
        if (post.equals("9S") || post.equals("文员")) {
            promotionUpVO.setPostClass(post);
        }
        return promotionUpVO;
    }

    public void deletePromotionById(String id) {
        mapper.deletePromotionById(id);
    }

    public int countStudy() {
        return mapper.countStudy(objValue6);
    }

    public String selectInformation() {
//        log.info("Redis正在查询学习计划概要缓存数据...");
//        List<String> countStudy = redisTemplate.getCountStudy();
//        if (countStudy.size() != 0){
//            log.info("Redis学习计划概要缓存数据命中成功!");
//            return countStudy;
//        }
//        log.info("Redis学习计划概要缓存数据命中失败,开始查询执行业务逻辑...");
//        StringBuilder sb = new StringBuilder();
//        List<String> list =  new ArrayList<>();
        // 整体合格率
//        return mapper.selectInformationAll(objValue6,common5);
        return mapper.selectInformationAll(common5);

//        Map<String,String> map = new HashMap<>();
//        List<String> strings = mapper.selectClassModel();
//        for (String string : strings) {
//            String ableCount = mapper.selectInformationByAble(objValue6,common5,string);
//            map.put(string,ableCount);
//        }
//        return map;

//        String sb2 = sb.toString();
//        System.out.println(sb2);
//        log.info("Mysql查询学习计划概要执行业务逻辑成功!");
//        log.info("向Redis加入学习计划概要缓存数据执行中...");
//        redisTemplate.saveCountStudy(list);
//        log.info("向Redis加入学习计划概要缓存数据执行成功!");
//        return list;
    }

    public String countPeople() {
        log.info("正在执行查询人员分布统计业务...");
        String information = redisTemplate.getCountPeopleInformation();
        if (information != null){
            log.info("人员分布统计信息redis缓存命中成功!");
            return information;
        }
        log.info("redis缓存命中失败,开始执行查询Mysql人员分布统计业务...");
        String str = mapper.countPeople();
        log.info("执行查询Mysql人员分布统计业务成功,开始向Redis缓存...");
        redisTemplate.saveCountPeopleInformation(str);
        log.info("redis缓存人员分布统计信息成功!");
        return str;
    }

    public List<String> selectInformationEchartsPercent() {
        List<String> allAbles = mapper.selectClassModel();
        List<String> values = new ArrayList<>();
        for (String able : allAbles) {
            String ableCount = mapper.selectInformationByAbles(objValue6,common5,able);
            if (ableCount == null){
                values.add("-");
                continue;
            }
            values.add(ableCount);
        }
        return values;
    }

    public List<String> selectInformationEchartsCount() {
        List<String> allAbles = mapper.selectClassModel();
        List<String> values = new ArrayList<>();
        for (String able : allAbles) {
            String ableCount = mapper.selectInformationByAbless(objValue6,common5,able);
            if (ableCount == null){
                values.add("-");
                continue;
            }
            values.add(ableCount);
        }
        return values;
    }

    public List<String> selectClassList() {
        return mapper.selectClassModel();
    }

    /**
     * 查询能力分布的辅助方法
     * @return
     */
    public Map<String,String> selectLeidaAble() {
        Map<String,String> returnMap = new HashMap<>();// 返回
        Map<String,List<String>> mapModel = new HashMap<>();
        List<String> trainingModel = mapper.selectClassModel();
        for (String training : trainingModel) {
            //
            List<String> list = mapper.selectAssessModelByTrainingModel(training);
            // 不做判断
            mapModel.put(training, list);
        }
        // 逻辑  管理  技能
        for (String test : trainingModel) { // 培训类型
            if (test == null || test.isEmpty()){
                continue;
            }
            String basicResult = "-" ;
            double pdResult = 0;
            double paResult = 0;
            double deResult = 0;
            double fiResult = 0;
            double reResult = 0;
            double pbpResult = 0;
            String result ;
            String numberYes = mapper.selectTrainingRecordByYes1Fu(test,common5); // 合格次数
            String numberAll= mapper.selectTrainingRecordByIdAllSFu(test,objValue6); // 总次数

            double eYTr = Double.parseDouble(numberYes);
            double eATr = Double.parseDouble(numberAll);
            if (eATr != 0) { // 证明有培训
                if (Double.parseDouble(numberYes) != 0) {
                    basicResult =
                            String.valueOf(Double.parseDouble(transformTwoNumber((eYTr / eATr) * 100)));
                }else{
                    basicResult = "0"; // 没一次合格
                }
            }
            // 波动因数
            List<String> assessList = mapModel.get(test);
            for (String assess : assessList) {  // 培训下属类型
                SelectResultVO srv = mapper.selectResultByAssessFu(assess);
                if (srv == null){
                    continue;
                }
                pdResult += srv.getPd()/250; // 减
                paResult += srv.getPa()/100; // 减
                deResult += srv.getDe()*10; // 减
                fiResult += srv.getFi()/150; // 减
                reResult += srv.getRe()/150; // 加
                pbpResult += srv.getPbp()/250; // 加
            }
            if (isNumber(basicResult)){
                // 有培训过
                result = Common.transformTwoNumber(Double.parseDouble(basicResult) +
                        (reResult + pbpResult) - (pdResult + paResult + deResult + fiResult));
            }else{
                result = "-";
            }
            returnMap.put(test,result);
        }
        return returnMap;
    }
    public Map<String,String> selectLeidaAbleFuVersion(String workshop) {
        Map<String,String> returnMap = new HashMap<>();// 返回
        Map<String,List<String>> mapModel = new HashMap<>();
        List<String> trainingModel = mapper.selectClassModel();
        for (String training : trainingModel) {
            List<String> list = mapper.selectAssessModelByTrainingModel(training);
            // 不做判断
            mapModel.put(training, list);
        }
        // 逻辑  管理  技能
        for (String test : trainingModel) { // 培训类型
            if (test == null || test.isEmpty()){
                continue;
            }
            String basicResult = "-" ;
            double pdResult = 0;
            double paResult = 0;
            double deResult = 0;
            double fiResult = 0;
            double reResult = 0;
            double pbpResult = 0;
            String result ;
            String numberYes = mapper.selectTrainingRecordByYes1FuFu(test,common5,workshop); // 合格次数
            String numberAll= mapper.selectTrainingRecordByIdAllSFuFu(test,objValue6,workshop); // 总次数
            double eATr = Double.parseDouble(numberAll);
            double eYTr = Double.parseDouble(numberYes);
            if (eATr != 0) { // 证明有培训
                if (Double.parseDouble(numberYes) != 0) {
                    basicResult =
                            String.valueOf(Double.parseDouble(transformTwoNumber((eYTr / eATr) * 100)));
                }else{
                    basicResult = "0"; // 没一次合格
                }
            }
            // 波动因数
            List<String> assessList = mapModel.get(test);
            for (String assess : assessList) {  // 培训下属类型
                SelectResultVO srv = mapper.selectResultByAssessFuFu(assess,workshop);
                if (srv == null){
                    continue;
                }

                pdResult += srv.getPd()/250; // 减
                paResult += srv.getPa()/100; // 减
                deResult += srv.getDe() * 10; // 减
                fiResult += srv.getFi()/150; // 减
                reResult += srv.getRe()/150; // 加
                pbpResult += srv.getPbp()/250; // 加
            }
            if (isNumber(basicResult)){
                // 有培训过
                result = Common.transformTwoNumber(Double.parseDouble(basicResult) +
                        (reResult + pbpResult) - (pdResult + paResult + deResult + fiResult));
                if (Double.parseDouble(result) >= 100){
                    result = "100";
                }else if (Double.parseDouble(result) < 0){
                    result = "0";
                }
            }else{
                result = "-";
            }
            returnMap.put(test,result);
        }
        return returnMap;
    }

    /**
     * 各车间培训统计 次数
     * @return
     */
    public List<String> selectInformationEchartsCountFuVersion(String workshop) {
        List<String> allAbles = mapper.selectClassModel();
        List<String> values = new ArrayList<>();
        for (String able : allAbles) {
            String ableCount = mapper.selectInformationByAblessFu(objValue6,common5,able,workshop);
            if (ableCount == null || ableCount.isEmpty()){
                values.add("-");
                continue;
            }
            values.add(ableCount);
        }
        return values;
    }
    public Map<String,Map<String,String>> selectAbleByWorkshop() {
        Map<String,Map<String,String>> returnMap = new HashMap<>();
        List<String> workshop = mapper.selectPulpingWorkshopFu();
        for (String workshopItem : workshop) {
            if (workshopItem == null || workshopItem.isEmpty()){
                continue;
            }
            Map<String, String> stringStringMap = selectLeidaAbleFuVersion(workshopItem);
            returnMap.put(workshopItem,stringStringMap);
        }
        return returnMap;
    }

    /**
     * 查询各车间培训的次数
     * @return
     */
    public Map<String,List<String>> selectPassByWorkshopCount() {
        Map<String,List<String>> returnMap = new HashMap<>();
        List<String> workshop = mapper.selectPulpingWorkshopFu();
        for (String workshopItem : workshop) {
            if (workshopItem == null || workshopItem.isEmpty()){
                continue;
            }
            List<String> strings = selectInformationEchartsCountFuVersion(workshopItem);
            returnMap.put(workshopItem, strings);
        }
        return returnMap;
    }

    /**
     * 查询每个车间的培训考试合格率
     * @return
     */
    public Map<String,List<String>> selectPassByWorkshopPass() {
        Map<String,List<String>> returnMap = new HashMap<>();
        List<String> workshop = mapper.selectPulpingWorkshopFu();
        for (String workshopItem : workshop) {
            if (workshopItem == null || workshopItem.isEmpty()){
                continue;
            }
            List<String> strings = selectInformationEchartsPercentFu(workshopItem);
            returnMap.put(workshopItem,strings);
        }
        return returnMap;
    }

    /**
     * 查询每个车间培训的合格率
     * @param workshop
     * @return
     */
    public List<String> selectInformationEchartsPercentFu(String workshop) {
        List<String> allAbles = mapper.selectClassModel();
        List<String> values = new ArrayList<>();
        for (String able : allAbles) {
            String ableCount = mapper.selectInformationByAblesFu(objValue6,common5,able,workshop);
            if (ableCount == null){
                values.add("-");
                continue;
            }
            values.add(ableCount);
        }
        return values;
    }

    public Map<String,List<String>> selectCountAssessAllByWorkshop(String workshop) {
        Map<String,List<String>> map = new HashMap<>();
        // 查询所有的违反类型
        List<String> list = mapper.selectViolateList();
        // 查询考核中,  按考核类型奖罚的次数
        for (String violate : list) { // 执行力
            // 次数
            List<String> listAdd = new ArrayList<>();
            String numberYes = mapper.selectAssessByViolateFu(violate,workshop,common3); // 次数
            String numberNo = mapper.selectAssessByViolateFu(violate,workshop,common4); // 次数
            // 只查加分
            SelectCountAssessAllVO point = mapper.selectAssessColumnByViolateOrPunishFu(violate,workshop);
            listAdd.add(numberYes); // 奖次数
            listAdd.add(numberNo); // 罚次数
            listAdd.add(point.getResult1()); // 绩效扣分
            listAdd.add(point.getResult2()); // 绩效扣比
            listAdd.add(point.getResult3()); // 罚款
            listAdd.add(point.getResult4()); // 现金奖励
            listAdd.add(point.getResult5()); // 绩效加分
            map.put(violate,listAdd);
        }
        return map;
    }

    /**
     * 查询整个部门的考核记录
     * @return
     */
    public Map<String,List<String>> selectCountAssessAllByWorkshopAll() {
        Map<String,List<String>> map = new HashMap<>();
        // 查询所有的违反类型
        List<String> list = mapper.selectViolateList();
        // 查询考核中,  按考核类型奖罚的次数
        for (String violate : list) { // 执行力
            // 次数
            List<String> listAdd = new ArrayList<>();
            String numberYes = mapper.selectAssessByViolateFuFu(violate,common3); // 次数
            String numberNo = mapper.selectAssessByViolateFuFu(violate,common4); // 次数
            // 只查加分
            SelectCountAssessAllVO point = mapper.selectAssessColumnByViolateOrPunishFuFu(violate);
            listAdd.add(numberYes); // 奖次数
            listAdd.add(numberNo); // 罚次数
            listAdd.add(point.getResult1()); // 绩效扣分
            listAdd.add(point.getResult2()); // 绩效扣比
            listAdd.add(point.getResult3()); // 罚款
            listAdd.add(point.getResult4()); // 现金奖励
            listAdd.add(point.getResult5()); // 绩效加分
            map.put(violate,listAdd);
        }
        return map;
    }

    public Map<String,Map<String,List<String>>> selectCountAssessAllWorkshop() {
        Map<String,Map<String,List<String>>> map = new HashMap<>();
        List<String> strings = mapper.selectPulpingWorkshopFu();
        for (String string : strings) {
            if (string == null || string.isEmpty()){
                continue;
            }
            Map<String, List<String>> stringListMap = selectCountAssessAllByWorkshop(string);
            map.put(string,stringListMap);
        }
        return map;
    }

    public String selectStudyListCount() {
        return mapper.selectStudyListCount(objValue6);
    }

    public Map<String,String> selectCountTrainingByWorkshop() {
        List<String> list = mapper.selectPulpingWorkshopFu();
        Map<String,String> map = new HashMap<>();
        for (String workshop : list) {
            if (workshop == null || workshop.isEmpty()){
                continue;
            }
            String result = mapper.selectCountTrainingByWorkshop(workshop);
            map.put(workshop,result);
        }
        return map;
    }

    public void deleteTestRecordById(String id) {
        mapper.deleteTestRecordById(id);
    }

    public void deleteStudyRecordById(String id) {
        mapper.deleteStudyRecordById(id);
    }

    public void deletePerformanceById(String id) {
        mapper.deletePerformanceById(id);
    }

    public String selectAutoCodeByModel(String model) {
        String maxCode = mapper.selectMaxCodeByModel(model);
        // ZJ001A
        if (maxCode == null || maxCode.isEmpty()){
            throw new NullPointerException("空指针警告,未匹配到与该类型相关的数据!");
        }
        String subString = maxCode.substring(maxCode.indexOf("J")+1,maxCode.length()-1).trim();
        String upCode = String.valueOf(Integer.parseInt(subString)+1);
        if (upCode.length() == 1){
            upCode = "00"+upCode;
        }
        if (upCode.length() == 2){
            upCode = "0"+upCode;
        }
        return maxCode.replace(subString,upCode);
    }

    public List<NewPlanVO> selectNewPlan(String id) {
        return mapper.selectNewPlan(id);
    }

    public void updateNewPersonPlanOverById(String id) {
        mapper.updateNewPersonPlanOverById(id);
    }

    public void submitInsertPersonPlan(List<SubmitPersonPlanDTO> list,String userId) {
        for (SubmitPersonPlanDTO submitPersonPlanDTO : list) {
            submitPersonPlanDTO.setUserId(userId);
            submitPersonPlanDTO.setState(true);
        }
        mapper.submitInsertPersonPlan(list);
    }

    public List<SubmitPersonPlanVO> selectPersonalPlanById(String id) {
        return mapper.selectPersonalPlanById(id,objValue73);
    }

    public void submitUpdatePersonPlan(String id) {
        mapper.submitUpdatePersonPlan(id, objValue71,objValue72);
    }

    public void submitDeletePersonPlan(String id) {
        mapper.submitDeletePersonPlan(id);
    }

    public List<StudyVO> queryTestList(QueryTestDTO dto) {
        if (dto.getModel().equals("计划中")){
            dto.setTh(false);
        }
        if (dto.getModel().equals("已完成")){
            dto.setTh(true);
        }
        return mapper.queryTestList(dto);
    }

    public List<StudyVO> queryStudyList(QueryStudyDTO dto) {
        if (dto.getModel().equals("计划中")){
            dto.setTh(false);
        }
        if (dto.getModel().equals("已完成")){
            dto.setTh(true);
        }
        return mapper.queryStudyList(dto);
    }

    public JsonPage<InsertAssessVO> queryPerformanceList(QueryPerformanceDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        return JsonPage.restPage(new PageInfo<>(mapper.queryPerformanceList(dto)));
    }

    public List<TrainingDataVO> querySubjectList(QuerySubjectDTO dto) {
        return mapper.querySubjectList(dto);
    }

    public void deleteTestById(Integer id) {
        mapper.deleteTestById(id);
    }

    public Object selectDoAssessPicture(List<SelectDoForeignPictureDTO> list) {
        // 分类
        Map<String,List<SelectDoForeignPictureDTO>> map = new HashMap<>();
        for (SelectDoForeignPictureDTO dto : list) {

        }
        return map;
    }
}